package org.ytor.core.sysapi.dynamicsql.logic;

import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.ytor.common.exception.BaseException;
import org.ytor.common.util.Jsons;
import org.ytor.common.util.Strs;
import org.ytor.core.sqlflow.BaseLogic;
import org.ytor.core.sysapi.dynamicsql.model.DynamicSqlConfig;
import org.ytor.core.sysapi.dynamicsql.repository.DynamicSqlConfigRepository;
import org.ytor.core.sysapi.dynamicsql.resp.DynamicSqlExecResp;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * created by  on 2025年5月22日 13:10:52
 * <br/>
 * DynamicSqlConfig服务
 * <br/>
 */
@Service
@RequiredArgsConstructor
public class DynamicSqlConfigLogic extends BaseLogic<DynamicSqlConfig, DynamicSqlConfigRepository> {

    public DynamicSqlExecResp execute(String id, Map<String, Object> params) {
        DynamicSqlConfig sqlConfig = repository.queryById(id);
        if (sqlConfig == null) {
            throw new BaseException("未找到对应的 SQL 配置: " + id);
        }
        if (sqlConfig.getStatus() != null) {
            throw new BaseException("该API已经停止，无法执行： " + id);
        }


        List<Map<String, Object>> results = new ArrayList<>();

        //TODO 对返回值进行处理
        DynamicSqlExecResp resp = new DynamicSqlExecResp();
        //查询结果
        resp.setResults(results);
        //列元信息
        if (!results.isEmpty()) {
            Map<String, Object> row = results.getFirst();
            resp.setRowMeta(row.keySet());
        }
        //参数和返回值备注
        Map<String, String> parameterRemark = Jsons.fromJsonStr(sqlConfig.getParameterRemark(), Jsons.MAP_OF_STRING_STRING);
        resp.setParameterRemark(parameterRemark == null ? new HashMap<>() : parameterRemark);
        Map<String, String> resultRemark = Jsons.fromJsonStr(sqlConfig.getResultRemark(), Jsons.MAP_OF_STRING_STRING);
        resp.setResultRemark(resultRemark == null ? new HashMap<>() : resultRemark);
        //接口注释
        resp.setRemark(sqlConfig.getRemark());
        return resp;
    }

    private String ensureLimit(String sql, Integer limit) {
        return sql + "\nlimit " + limit;
    }

    private String buildMapperXml(String id, String sqlFragment, String parameterType, String resultType) {
        if (Strs.isEmpty(parameterType)) {
            parameterType = "map";
        }
        if (Strs.isEmpty(resultType)) {
            resultType = "java.util.HashMap";
        }
        return "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n" +
                "<!DOCTYPE mapper PUBLIC \"-//mybatis.org//DTD Mapper 3.0//EN\" " +
                "\"http://mybatis.org/dtd/mybatis-3-mapper.dtd\">\n" +
                "<mapper namespace=\"DynamicSqlMapper\">\n" +
                "<select id=\"" + id + "\" parameterType=\"" + parameterType + "\" resultType=\"" + resultType + "\">\n" +
                sqlFragment + "\n" +
                "</select>\n</mapper>";
    }

}